package com.hoopchina.ui.home;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;

/**
 * CityEngine
 * 用于城市列表数据库
 * 
 * @author Neusoft
 */
public class CityEngine {
    // private static final int VERSION = 1;
    private Context                     mContext  = null;
    private CityDatabaseHelper          mDBHelper = null;
    
    /**
     * 初始化类的各项参数
     * @param context
     */
    public CityEngine( Context context ) {
        mContext = context;
        mDBHelper = new CityDatabaseHelper( mContext, "cities_db" );
        try {
            mDBHelper.getReadableDatabase();
        }
        catch ( SQLiteException e ) {
            e.printStackTrace();
        }
        finally {
            if ( null != mDBHelper ) {
                mDBHelper.close();
            }
        }
    }

    /**
     * 获得某省的城市列表
     */
    public  String[] getCitys(int pc1, int pc2) {
    	 String[] args = {pc1 + "" , pc2 + ""};
    	 String[] cityArray = null;
    	 
        try {
            SQLiteDatabase db = mDBHelper.getWritableDatabase();
            Cursor cursor = db.rawQuery( "select cityName from city_table where cityCode > ? and cityCode < ?;", args );
            cityArray = new String[cursor.getCount()];
            int i = 0;
            while ( cursor.moveToNext() ) {
                String cityName = cursor.getString( cursor.getColumnIndex( "cityName" ) );
                cityArray[i++] = cityName;
            }
            mDBHelper.close();
            return cityArray;
        }
        catch ( SQLException e ) {
            if ( null != mDBHelper ) {
                mDBHelper.close();
            }
            e.printStackTrace();
        }
        return new String[0];
    }

    /**
     * 根据某城市的名称获得城市编码
     * @param city
     * @return
     */
    public  String getCityCode(String city) {
   	 	String[] args = {city};
        String cityCode = null;

       try {
           SQLiteDatabase db = mDBHelper.getWritableDatabase();
           Cursor cursor = db.rawQuery( "select cityCode from city_table where cityName=?;", args );

           while ( cursor.moveToNext() ) {
               cityCode = cursor.getString( cursor.getColumnIndex( "cityCode" ) );
           }
           mDBHelper.close();
       }
       catch ( SQLException e ) {
           if ( null != mDBHelper ) {
               mDBHelper.close();
           }
           cityCode = null;
           e.printStackTrace();
       }
       return cityCode;
   }

    
}
